7.6 Timers

  1. Motivations
  2. Timers
    • The window object supports many useful features. One of them is timer.
    • There are two types of timer - one time timer and repeating timer.
    • One time timer - Read all in Window setTimeout() Method.
      • How to clear the timer? clearTimeout(timerid)
    • Repeating timer - Read all in Window setInterval() Method.
      • How to clear the timer? clearInterval(timerid)
    • Can you display a timer on the n-puzzle game, that displays the elapsed time? Let's try now.    
      <script>
          ??? count;
          function start() {
              document.???('start_button').??? (???, function() {
                  count = ???;
                  window.setInterval(function() {
                      count???;
                      ???.getElementById('seconds').??? = count;
                  },???);  // Every 1 second
              };
          }
          ???.???(???, start);  // When the body is completely loaded.
      </script>
      
      <body>
          <button id='start_button'>Start the game</button><br>
          <p>Elapsed time: <span id='seconds></span></p>
      </body>
      
    • Trial 1: Let's try to make timer. The timer is invoked every second.


    • Trial 2: Let's try to make a wakeup call. You will be called after 10 seconds. Which type timer do you need to use?
      Let's use .setTimeout().


    • Trial 3: Let's try to make a wakeup call. You will be called if there is no activity for 10 seconds. What activity?
      Let's use .setTimeout() and two events - mousemove and keydown.



  3. Learning outcomes